<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>

</head>
<input>
  <input type="file" id="imageSelect" />
  <button id="imageTransform">改变图片颜色</button>
  <canvas id="imagePreview" width="1024" height="768"></canvas>
</body>
<script>
  const imageSelect = document.getElementById('imageSelect')
  imageSelect.addEventListener('change', event => {
    console.log(imageSelect.files[0])
    const file = imageSelect.files[0]
    const { type } = file
    if (!type.startsWith('image')) {
      return
    }
    const reader = new FileReader()
    reader.readAsDataURL(file)
    const imagePreview = document.getElementById('imagePreview')
    reader.onload = function (event) {
      const src = event.target.result
      const image = new Image()
      image.src = src
      image.onload = function() {
        const ctx = imagePreview.getContext('2d')
        ctx.drawImage(this, 0, 0)

      }
    }

    document.getElementById('imageTransform').addEventListener('click', () => {
      const imagePreview = document.getElementById('imagePreview')
      const ctx = imagePreview.getContext('2d')
      const myImage = ctx.getImageData(0, 0, 1024, 768);
      const length = 1024 * 768
      for (var i = 0; i < length * 4; i += 4) {
        const myRed = myImage.data[i];
        const myGreen = myImage.data[i + 1];
        const myBlue = myImage.data[i + 2];
        const myGray = parseInt((myRed + myGreen + myBlue) / 3);
        myImage.data[i] = myGray;
        myImage.data[i + 1] = myGray;
        myImage.data[i + 2] = myGray;
      }
      ctx.putImageData(myImage, 0, 0)
    })
  })
</script>
</html>